/**
* @description: 印章使用工单 --》发起申请 （班组负责人）
* @author: JiWei
* @date:
**/
<template>
	<view class="task-monitor-main">
		<!-- <nav-bar class="header" back title="工单发起" @goBack="goBack" /> -->
		<nav-bar class="header" back title="工单发起" @goBack="goBack">
		  <img slot="screen" src="../../../static/img/sx.png" alt="" @click="screen" v-if="currentIndex === '1'">
		</nav-bar>
		<view class="header-bar">
			<!-- 切换tab -->
			<div class="get-state-tab">
				<div class="info-tab-item" :class="currentIndex === '0' ? ' info-tab-current': ''"
					@click="tabChange('0')">工单发起</div>
				<div class="info-tab-item" :class="currentIndex === '1' ? ' info-tab-current': ''"
					@click="tabChange('1')">我发起的</div>
			</div>
		</view>
		<view v-if="currentIndex === '0'">
			<!-- main   -->
			<main>
				<van-form ref="ruleForm">
					<view class="main-top">

						<van-field v-model="useDate" label="用章日期" placeholder="请选择用章日期"
							:rules="[{ required: true, trigger:'onSubmit'}]" input-align="right" required
							right-icon="arrow" error-message-align="right" @click="onOpenPicker('useDate')" readonly/>
						<van-field clickable input-align="right" required v-model="useNum"
							:rules="[{ required: true, trigger:'onSubmit'},{pattern,message:'请输入数字'}]" label="用印份数" placeholder="请输入"
							error-message-align="right" />
					</view>
					<view class="remark-info-container">
						<view><text style="color: #f00">*</text>用章事由(文件名称)</view>
						<van-divider dashed />
						<div class="remark-wrap-yz">
							<van-field :rules="[{ required: true, trigger:'onSubmit'}]" error-message-align="right"
								type="textarea" class="remark-text" v-model="originIncident" placeholder="这里是用章事由信息" />
						</div>
					</view>
					<view class="remark-info-container">
						<view>备注</view>
						<van-divider dashed />
						<div class="remark-wrap-yz">
							<van-field error-message-align="right" type="textarea" class="remark-text" v-model="remarks"
								placeholder="这里是备注信息" />
						</div>
					</view>
					<view class="main-top">
						<van-field disabled clickable input-align="right" v-model="originatorName" required
							:rules="[{ required: true, trigger:'onSubmit'}]" label="申请人" placeholder="请输入"
							error-message-align="right" />
						<van-field clickable input-align="right" disabled v-model="trusteeName" 
							:rules="[{ required: false, trigger:'onSubmit'}]" label="经办人" placeholder="请选择"
							right-icon="arrow" error-message-align="right"
							@click-right-icon="handleSelectUser('trustee')" />
						<van-field clickable input-align="right" disabled v-model="approverName" required
							:rules="[{ required: true, trigger:'onSubmit'}]" label="审批人" placeholder="请选择"
							right-icon="arrow" error-message-align="right"
							@click-right-icon="handleChooseUser('approver')" />
					</view>
				</van-form>
			</main>
			<!-- footer   -->
			<footer>
				<van-button block @click="submit">提交</van-button>
			</footer>
			<van-popup v-model="showPicker" position="bottom">
				<van-datetime-picker :type="datepickertype" :formatter="formatter" cancel-button-text="清空"
					@confirm="onDatetimeConfirm" @cancel="onDatetimeEmpty" v-model="currentDate" :min-date="minDate" />
			</van-popup>
			<van-popup v-model="showSelectUser" position="right">
				<selectUserApproveyz :trusteeId="trusteeId" :selected.sync="staffList" @cancel="onSelUserCancel" />
			</van-popup>
			<van-popup v-model="showChooseUser" position="right">
				<selectUserApprovezsyz :approverId="approverId" :selected.sync="staffList" @cancel="onChooseCancel" />
			</van-popup>
		</view>
		<view v-else class="main-container">
			<view class="header-bar list-header">
				<ul class="menu">
					<li v-for="(item,index) in menuList" :key="index" @click="chooseMenu(item, index)">
						<view class="right-box">
							<text class="menu-num" :class="{selectmenu:index === current}">{{ item.value }}</text>
							<text class="menu-state" :class="{selectmenu:index === current}">{{ item.title }}</text>
						</view>
						<view :class="{sj:index === current}"></view>
					</li>
				</ul>
			</view>
			<view class="task-list-container" v-if="approvalList.length > 0">
				<van-pull-refresh v-model="refreshing" @refresh="onRefresh">
				  <van-list v-model="isLoading" :finished="finished" finished-text="没有更多了" @load="loadMore">
				    <!-- 列表循环   -->
				    <view class="task-list" v-for="(item,index) in approvalList" :key="index" @click="jump(item)">
				      <van-swipe-cell >
				        <view class="task-title">
				          <view class="task-title-main">
				            <text class="task-title-main-text">{{ item.ORIGINATOR_NAME }}发起的印章审批</text>
				          </view>
				          <text class="task-status" :class="color(item.STATE)">
				            <text>{{item.STATENAME}}</text>
				          </text>
				        </view>
				        <hr class="task-hr">
				        <view class="top-task-main">
				          <text class="task-big-ltitle">发起人:</text>
				          <text class="task-small-ltitle">{{ item.ORIGINATOR_NAME }}</text>
				          <text class="task-big-rtitle">发起时间:</text>
				          <text class="task-small-rtitle">{{ item.TIME }}</text>
				        </view>
				        <template #right v-if="item.STATENAME === '已撤销'">
				          <van-button class="delBtn" @click="handleDel(item)"  type="danger" text="删除" />
				        </template>
				      </van-swipe-cell>
				    </view>
				  </van-list>
				</van-pull-refresh>
			</view>
			<!--筛选弹窗-->
			<screenPopup :showScreen="showScreen" @closePopup="showScreen=false" @confirm="confirmCondition"
				:otherList="otherList" :typeList="typeList" @reset="reset">
			</screenPopup>

		</view>
	</view>
</template>
<script>
	import navBar from "../../../components/common/nav-bar";
	import moment from "moment/moment";
	import selectUserApproveyz from '../common/selectUserApproveyz'
	import selectUserApprovezsyz from '../common/selectUserApprovezsyz.vue'
	import screenPopup from "../common/screenPopup2.vue";
	import {
		Dialog,
		Toast
	} from "vant";
	import {
		mapGetters
	} from "vuex";

	export default {
		name: 'initiateApplication',
		components: {
			navBar,
			selectUserApproveyz,
			selectUserApprovezsyz,
			screenPopup
		},
		props: {},
		data() {
			return {
				pattern:/^[0-9]*$/,
				current: 0, // 当前选中的任务类型tab
				state: '审批通过',
				stateCode: '3',
				menuList: [],
				approvalList: [],
				refreshing: false, // 是否正在刷新
				isLoading: false,
				finished: false,
				total: 0, // 总条数
				approvalPage: 1,
				approvalLimit: 20,
				current: 0, // 当前选中的任务类型tab
				originatorName: '', //申请人
				originatorId: '', // 申请人
				useDate: '', //用印日期
				useNum: '', //用印份数
				originIncident: '', //用意事由
				remarks: '', //备注
				trusteeName: '', //经办人
				trusteeId: '', //经办人
				approverName: '', //审批人
				approverId: '', //审批人
				timeString: '',
				currentDate: '',
				datepickertype: 'date',
				showPicker: false,
				currentIndex: "0",
				minDate: new Date(0),
				textareaValue: '', // 备注
				showSelectUser: false,
				showChooseUser: false,
				staffList: {
					ids: [],
					text: ''
				},
				isChoosable: false, // 是否可进行选择
				equText: '',
				equIds: [], // 光缆设备人员
				optText: '',
				optIds: [], // 电源设备人员
				id: '',
				color: (STATE) => {
				  if (STATE === '0') {
				    return 'left-state-dsp'
				  } else if (STATE === '1') {
				    return 'left-state-jj'
				  } else if (STATE === '2') {
				    return 'left-state-ywc'
				  } else {
				    return 'left-state-ycx'
				  }
				},
				showScreen: false,
				typeList: [
					{
						TITLE: '本周',
						VALUE: 1,
					},
					{
						TITLE: '本月',
						VALUE: 2,
					},
					{
						TITLE: '上月',
						VALUE: 3,
					}
				],
				otherList: [{
						TITLE: '按天',
					},
					{
						TITLE: '按月',
					}
				],
				timeType:1,
			};
		},
		computed: {
			...mapGetters(['userData']),
			
		},
		watch: {
			staffList: {
				handler: function(newVal) {
					let staffIdsType = this.staffType + 'Id' // equIds optIds powIds
					let staffTextType = this.staffType + 'Name' // equText optText powText

					this[staffIdsType] = newVal.ids
					this[staffTextType] = newVal.text
				},
				immediate: true,
				deep: true
			}
		},
		onLoad(option) {
			this.originatorName = this.userData.SUERNAME;
			this.originatorId = this.userData.USERID;
			if (option.id) {
				this.id = option.id;
				this.getProvincialSealDetailed();
			}
			this.getSealList();
		},

		methods: {
			handleDel(item) {
			  let params = {
			    ID:item.ID,
			    userId: this.userData.USERID
			  }
			  Dialog.confirm({
			    message: "是否确认删除？",
			  }).then(() => {
			    this.$api.deleteSealOne(params).then(res => {
			      if(res.code == 0) {
			        Toast.success({
			          message:'删除成功'
			        })
			        this.onRefresh()
			      }else {
			        Toast('删除失败')
			      }
			    })
			  })
			
			},
			confirmCondition(selected, beginTime, endTime) {
				this.timeType = selected // 发起时间
				this.startTime = beginTime
				this.endTime = endTime
				this.onRefresh()
			},
			screen() {
				this.showScreen = true;
			},
			loadMore() {
			  if (this.total > this.approvalList.length) {
			    this.approvalPage = this.approvalPage + 1;
			    this.getSealList();
			  } else {
			    this.finished = true;
			  }
			},
			// 获取审批列表
			getSealList() {
				  
				let params = {
					state: this.current !== 0 ? String(this.current - 1) : '',
					userId: this.userData.USERID, // 是	string	登录用户ID
					timeType: this.timeType,
					startTime: this.startTime,
					endTime: this.endTime,
					name: this.searchValue, // 否	string	任务名称
					limit: this.approvalLimit, // 否	string	分页条数 不传查全部
					page: this.approvalPage, // 否	string	分页页数 不传查全部
				}
				this.$api.getSealList(params).then(res => {
					this.isLoading = false;
					this.refreshing = false;
					this.approvalList = this.approvalList.concat(res.data.resList.map((item) => {
						return {
							TIME: item.CREATE_TIME ? moment(item.CREATE_TIME).format(
								'YYYY-MM-DD HH:mm') : '',
							isChecked: false,
							...item
						}
					}))
					  

					this.menuList = [{
							title: '全部',
							value: res.data.count.total
						},
						{
							title: '待审批',
							value: res.data.count.pending
						},
						{
							title: '审批通过',
							value: res.data.count.pass
						},
						{
							title: '审批拒绝',
							value: res.data.count.fail
						}
					]

				})
			},
			chooseMenu(item, index) {
				this.current = index
				this.currrentTaskState = item.taskState;
				this.iconUrl = require('../../../static/img/batch.png');
				// this.chooseText = '批量审批';
				this.isChoosable = false;
				this.onRefresh()
			},
			onRefresh() {
				this.refreshing = true;
				this.finished = false;
				this.approvalPage = 1;
				this.approvalList = [];
				this.getSealList();
			},
			getProvincialSealDetailed() {
				let params = {
					id: this.id
				}
				this.$api.getProvincialSealDetailed(params).then(res => {
					this.useDate = res.data.USE_DATE;
					this.useNum = res.data.USE_NUM;
					this.originIncident = res.data.ORIGIN_INCIDENT;
					this.remarks = res.data.REMARKS;
					this.originatorName = res.data.ORIGINATOR_NAME;
					this.trusteeName = res.data.TRUSTEE_NAME;
					this.approverName = res.data.APPROVE_NAME;
					this.approverId = res.data.APPROVE_ID;
				})
			},
			formatter(type, val) {
				if (this.datepickertype === "date") {
					if (type === 'year') {
						return `${val}年`;
					} else if (type === 'month') {
						return `${val}月`;
					} else if (type === 'day') {
						return `${val}日`;
					}
				}
			},
			tabChange(currentIndex) {
				this.currentIndex = currentIndex;
				// this.onRefresh()
			},

			onDatetimeEmpty() {
				this.useDate = ''
				this.showPicker = false
			},
			onOpenPicker(pickerType) {
				if (pickerType === 'useDate') {
					this.currentDate = this.useDate !== '' ? new Date(this.useDate) : new Date()
				}
				this.showPicker = true
			},
			jump(item) {
			  uni.navigateTo({
			    url: `/pages/operationApprove/sealApproval/sealDetailsApproval?id=${item.ID}&pagetype=${'initial'}`
			  });
			},
			onDatetimeConfirm(time) {
				let timeString = "";
				timeString = this.datepickertype === "date" ? moment(time).format('YYYY-MM-DD') : moment(time).format(
					'YYYY-MM')
				this.useDate = timeString
				this.showPicker = false
			},
			// 返回
			goBack() {
				// uni.navigateTo({
				// 	url: '/pages/operationApprove/sealApproval/sealApprovalTeam'
				// })
				uni.navigateBack()
			},
			onSelUserCancel() {
				this.showSelectUser = false
			},
			onChooseCancel() {
				this.showChooseUser = false
			},
			handleSelectUser(t) {
				this.showSelectUser = true
				this.staffType = t
				if (this.staffType == 'trustee') {
					// 经办人
					this.staffList = {
						ids: !this.trusteeName ? [] : this.trusteeId,
						text: this.trusteeName
					}
				}
			},
			handleChooseUser(t) {
				this.showChooseUser = true
				this.staffType = t
				if (this.staffType == 'approver') {
					// 审批人
					this.staffList = {
						ids: !this.approverName ? [] : this.approverId,
						text: this.approverName
					}
				}
			},
			submit() {
				let _this = this;
				  
				this.$refs.ruleForm.validate().then(() => {
					  
					let params = {
						originatorName: this.originatorName,
						originatorId: this.originatorId,
						useDate: this.useDate,
						useNum: this.useNum,
						originIncident: this.originIncident,
						remarks: this.remarks,
						trusteeName: this.trusteeName,
						trusteeId: this.trusteeId !== null ? this.trusteeId.toString() : this.trusteeId,
						approverName: this.approverName,
						approverId: this.approverId !== null ? this.approverId.toString() : this.approverId,
					}
					Dialog.confirm({
						message: "是否确认提交？",
					}).then(() => {
						this.$api.initiateWork(params).then(res => {
							if (res.code == 0) {
								Toast.success({
									message: '发起成功',
									onOpened: () => {
										uni.navigateTo({
											url:'/pages/operationApprove/index/index',
										})
									}
								})
							} else {
								Toast.success({
									message: '发起失败'
								})
							}
						})
					})
				}).catch((error) => {
					  
					Toast('请完善内容');
				})

			}
		}
	};
</script>
<style scoped lang="scss">
	.task-monitor-main {
		min-height: 100vh;
		background: #F2F6FA;
		overflow: hidden;
		.header {
		  position: sticky;
		  top: 0;
		
		  img {
		    width: px2vw(48);
		    margin-right: px2vw(40);
		  }
		
		  .header-right {
		    display: flex;
		
		    /deep/ .van-icon {
		      font-size: px2vw(52);
		      font-weight: bold;
		    }
		
		    /deep/ .van-icon-scan {
		      margin-right: px2vw(12);
		    }
		
		    /deep/ .van-icon-filter-o {
		      margin-left: px2vw(12);
		    }
		  }
		}
		.header-bar {
			height: px2vh(220);
			border-radius: 0 0 px2vh(40) px2vh(40);
			background: #417ADC;
			margin-bottom: px2vh(20);
			display: flex;
			justify-content: center;

			.get-state-tab {
				width: calc(100% - #{px2vw(60)});
				height: px2vh(120);
				border-radius: px2vw(20);
				box-sizing: border-box;
				// margin: px2vh(40) px2vw(30) px2vh(37);
				background-color: rgba(255, 255, 255, 0.4);
				display: flex;
				justify-content: center;
				align-items: center;
				border: px2vw(2) solid rgba(198, 215, 245, 1);

				.info-tab-item {
					width: 50%;
					display: flex;
					justify-content: center;
					align-items: center;
					color: rgba(255, 255, 255, 1);
					font-weight: bold;
					font-size: px2vw(38);

					&.info-tab-current {
						height: px2vh(100);
						margin: 0 px2vw(10);
						margin-right: px2vw(10);
						border-radius: px2vw(20);
						background-color: rgba(255, 255, 255, 0.7);
						color: rgba(65, 122, 220, 1);
						font-weight: Bold;
					}
				}
			}
		}

		main {
			margin-top: px2vh(30);
			width: calc(100% - #{px2vw(60)});
			margin-left: px2vw(30);
			height: calc(100vh - #{px2vh(620)});
			overflow-x: auto;

			.main-top {
				overflow: hidden;
				border-radius: px2vh(20);
				margin-bottom: px2vh(30);
			}

			.remark-info-container {
				padding: px2vh(70) px2vw(50);
				font-size: px2vw(42);
				color: #666666;
				border-radius: px2vw(20);
				overflow: hidden;
				background-color: #FFFFFF;
				margin-top: px2vh(40);
				margin-bottom: px2vh(40);

				.remark-wrap {
					padding: px2vh(41) px2vw(56) px2vh(77) px2vw(55);
					border-radius: px2vw(20);

					.remark-text {
						height: px2vh(150);
					}
				}

				.remark-wrap-yz {
					border-radius: px2vw(20);

					.remark-text {
						height: px2vh(150);
					}
				}
			}
		}

		footer {
			height: px2vh(155);
			background: #f2f6fa;
			padding-top: px2vh(45);

			/deep/ .van-button {
				width: calc(100% - #{px2vw(60)});
				margin-left: px2vh(30);
				height: px2vh(120);
				color: #fff;
				background-color: #417ADC;
				border: 1px solid #417ADC;
				border-radius: px2vh(60);
			}
		}

		.header-bar {
			// height: px2vh(120);
			border-radius: 0 0 px2vh(40) px2vh(40);
			background: #417ADC;
			// margin-bottom: px2vh(130);

			.menu {
				width: px2vw(1020);
				height: px2vh(220);
				// background-image: url('../../../static/img/borderR.png');
				background: #fff;
				background-size: px2vw(1020) px2vh(220);
				//margin-left: px2vw(30);
				margin: 0 auto;
				display: flex;
				justify-content: space-evenly;

				li {
					//width: calc(1 * (100% - #{px2vw(400)}) / 4);
					height: 100%;
					//margin-left: px2vw(80);
					//float: left;
					position: relative;

					.right-box {
						height: px2vh(112);
						//margin-left:px2vw(10);
						float: left;
						margin-top: px2vh(59);
						text-align: center;

						.menu-num {
							display: block;
							font-size: px2vw(54);
							font-weight: bold;
							color: #333;
						}

						.menu-state {
							font-size: px2vw(36);
							color: #333;
						}

						.selectmenu {
							color: #417ADC;
						}
					}

					.sj {
						width: px2vw(78);
						height: px2vh(66);
						position: absolute;
						bottom: px2vh(-34);
						//right: px2vw(40);
						left: 50%;
						transform: translateX(-50%);
						background-image: url('../../../static/img/sj.png');
						background-size: px2vw(78) px2vh(66);
					}
				}
			}

		}

		.list-header {
			background-color: transparent !important;
		}

		.main-container {
			height: calc(100vh - #{px2vh(413)});
			position: relative;

			.submit-wrap {
				width: calc(100vw - #{px2vw(60)});
				padding: px2vh(0) px2vw(30);
				text-align: center;
				position: fixed;
				bottom: 20px;

				/deep/ .van-button {
					width: 100%;
					height: px2vh(120);
					color: #fff;
					background-color: #417ADC;
					border: 1px solid #417ADC;
					border-radius: px2vh(60);
				}
			}
			.task-list-container {
				height: calc(100vh - #{px2vh(443)} - 38px - #{px2vh(165)});
				overflow: auto;
				position: relative;

				.task-list {
				  width: px2vw(1020);
				  background: #fff;
				  border-radius: px2vw(20) px2vh(20);
				  margin: 0 px2vw(30) px2vh(30) px2vw(30);
				
				  .task-title {
				    width: px2vw(940);
				    height: px2vh(80);
				    margin-left: px2vw(40);
				    padding-top: px2vw(30);
				    margin-bottom: px2vh(30);
				    display: flex;
				    align-items: center;
				    justify-content: space-between;
				
				    .task-title-main {
				      display: flex;
				      align-items: center;
				
				      img {
				        width: px2vw(64);
				        height: px2vw(64);
				      }
				    }
				
				    .task-title-main-text {
				      width: px2vw(700);
				      white-space: nowrap;
				      overflow: hidden;
				      text-overflow: ellipsis;
				      margin-left: px2vw(20);
				      font-size: px2vh(48);
				    }
				
				    .task-status {
				      width: px2vw(200);
				      height: px2vh(50);
							      line-height: px2vh(50);
				      border-radius: px2vw(10);
				      font-size: px2vw(32);
				      text-align: center;
				    }
				
				    .left-state-ywc {
				      color: #3CDA68;
				      background: rgba(60, 218, 104, .1);
				    }
				
				    .left-state-dsp {
				      color: #FFAD0E;
				      background: rgba(255, 173, 14, .1);
				    }
				
				    .left-state-jj {
				      color: #FF7070;
				      background: rgba(255, 112, 112, .1);
				    }
				
				    .left-state-dzx {
				      color: #417ADC;
				      background: rgba(65, 122, 220, .1);
				    }
				
				    .left-state-ycx {
				      color: #8C8C8C;
				      background: rgba(140, 140, 140, .1);
				    }
				  }
				
				  .task-hr {
				    width: px2vw(940);
				    border: px2vh(1) solid #e5e5e5;
				    margin-left: px2vw(40);
				    margin-bottom: px2vh(30);
				  }
				  .delBtn {
				    height: 100%;
				    background: #FF4355;
				    border-radius: px2vw(0) px2vw(20) px2vw(20) px2vw(0);
				  }
				  .top-task-main {
				    width: px2vw(900);
				    font-size: px2vh(36);
				    line-height: px2vh(62);
				    margin-left: px2vw(60);
				    padding-bottom: px2vw(30);
				    .task-big-ltitle,
				    .task-big-rtitle {
				      color: #666;
				    }
				    .task-small-ltitle,
				    .task-small-rtitle {
				      margin-left: px2vw(25);
				      color: #333;
				    }
				    .task-big-rtitle {
				      margin-left: px2vw(40);
				    }
				  }
				}
			}
		}
	}
</style>
